import os
from ivic.core import Config, project_path
from ivic.core import Logging

from ivic.webfarm.Server import *
from ivic.webfarm.Monitor import *

logger = Logging.get_logger('ivic.webfarm.Plugin')

__webfarm = None
__monitor = None

def init(daemon_config):
    #loading config
    config = Config.load(project_path('/etc/ivic/webfarm.yaml'))
    
    #specify the logging Instance
    Logging.get_logger('ivic.webfarm.Plugin', filename=config['log_file'])
    Logging.get_logger('ivic.webfarm.WebFarmUtils', filename=config['log_file'])
    Logging.get_logger('ivic.webfarm.Server', filename=config['log_file'])
    Logging.get_logger('ivic.webfarm.WorkNode', filename=config['log_file'])
    Logging.get_logger('ivic.webfarm.Monitor', filename=config['log_file'])
    
    logger.debug('initializing %s' % __name__)
    
    global __webfarm
    if __webfarm:
        logger.error('[WebFarmServer]reinitialized is not supported')
        return
    
    logger.debug('init webfarm server.')
    __webfarm = WebFarmServer(config)
    
    global __monitor
    if __monitor:
        logger.error('[Monitor]reinitialized is not supported')
        return
    
    logger.debug('init webfarm monitor.')
    __monitor = Monitor(__webfarm.nodes_mgr, config['report_url'])
    __monitor.start()
    logger.debug('ivic-webfarm monitor started.')
     
def fini():
    global __webfarm
    del __webfarm
    
    try:
        global __monitor
        __monitor.stop()
        __monitor.join()
        del __monitor
    except Exception, e:
        logger.error('%s' % e)
    
def soap_mods():
    global __webfarm
    return {'/webfarm': __webfarm}

def wsgi_mods():
    return {}
